package com.situ.firmadmin.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;

import com.situ.firmadmin.annotation.MyLog;
import com.situ.firmadmin.pojo.*;
import com.situ.firmadmin.pojo.dto.UserPasswordDTO;
import com.situ.firmadmin.pojo.dto.UserLoginDTO;
import com.situ.firmadmin.pojo.query.UserQuery;
import com.situ.firmadmin.pojo.vo.TypeCountVO;
import com.situ.firmadmin.service.*;
import com.situ.firmadmin.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IUserService userService;
	@Autowired
	private ILoginLogService loginLogService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	private IAddressService addressService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private IAuthService authService;
	
	@MyLog(module = "用户管理-列表")
	@GetMapping("/list")
	public Result selectByPage(UserQuery userQuery) {
		User user=userService.getUser();
		PageResult pageResult = userService.selectByPage(userQuery,user);
		Map<String, Object> map = new HashMap<>();
		map.put("total", pageResult.getCount());
		map.put("list", pageResult.getData());
		return Result.ok(map);
	}
	
	@PostMapping("/login")
	public Result login(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request, HttpServletResponse resp) {
		//判断验证码是否正确
		String captcha = (String) redisTemplate.opsForValue().get(CommonUtil.getCaptchaKey(request));
		//判断验证码是否有效
		if (StringUtils.isEmpty(captcha)) {
			return Result.error("验证码已失效");
		}
		if (!captcha.equalsIgnoreCase(userLoginDTO.getCaptcha())) {
			return Result.error("验证码错误！");
		}
		
		User user = userService.login(userLoginDTO.getName());
		
		if (user == null) {
			LoginLog loginLog = new LoginLog();
			loginLog.setAdminName(userLoginDTO.getName());
			loginLog.setStatus(0);
			loginLog.setMsg("用户名不存在");
			loginLog.setIp(JakartaServletUtil.getClientIP(request));
			loginLogService.add(loginLog);
			return Result.error("用户名不存在!");
		}
		//判断密码是否正确
		if (!MD5Util.MD5Encode(userLoginDTO.getPassword()).equals(user.getPassword())) {
			return Result.error("密码错误！");
		}
		
		if (user.getStatus() == 0) {
			LoginLog loginLog = new LoginLog();
			loginLog.setAdminName(user.getName());
			loginLog.setAdminId(user.getId());
			loginLog.setStatus(0);
			loginLog.setMsg("该用户被禁用");
			loginLog.setIp(JakartaServletUtil.getClientIP(request));
			loginLogService.add(loginLog);
			return Result.error("该用户被禁用");
		}
		
		LoginLog loginLog = new LoginLog();
		loginLog.setAdminName(user.getName());
		loginLog.setStatus(1);
		loginLog.setAdminId(user.getId());
		loginLog.setMsg("登录成功！");
		loginLog.setIp(JakartaServletUtil.getClientIP(request));
		loginLogService.add(loginLog);
		//构建Token
		Map<String, Object> map = new HashMap<>();
		map.put("id", user.getId());
		map.put("name", user.getName());
		String token = JwtUtil.createToken(map);
		return Result.ok("登录成功！", token);
	}
	
	@GetMapping("/userInfo")
	public Result userInfo(@RequestHeader(name = "Authorization") String token) {
		String name = (String) JwtUtil.parseToken(token).get("name");
		User user = userService.getOne(name);
		return Result.ok(user);
	}
	
	@MyLog(module = "用户管理-添加")
	@PostMapping("/add")
	public Result add(@RequestBody User user) {
		if(user.getPassword()!=null && user.getPassword()!=""){
			String password = MD5Util.MD5Encode(user.getPassword());
			user.setPassword(password);
		}
		if(user.getProvinceId()!=null){
			String address = (addressService.selectProvince(user.getProvinceId())).getName() + "-";
			address += (addressService.selectCity(user.getCityId())).getName() + "-";
			address += (addressService.selectArea(user.getAreaId())).getName();
			user.setAddress(address);
		}
		userService.insert(user);
		return Result.ok("添加成功！");
	}
	
	@DeleteMapping("/deleteById/{id}")
	public Result deleteById(@PathVariable Integer id) {
//        User user=userService.selectById(id);
		userService.deleteById(id);
//        AliOSSUtil.deleteFile(user.getImage());
		return Result.ok("删除成功！");
	}
	
	@DeleteMapping("/deleteAll/{ids}")
	public Result deleteAll(@PathVariable Integer[] ids) {
		userService.deleteAll(ids);
		return Result.ok("删除成功！");
	}
	
	@GetMapping("/selectById/{id}")
	public Result selectById(@PathVariable Integer id) {
		User user = userService.selectById(id);
		return Result.ok(user);
	}
	
	@PutMapping("/update")
	public Result update(@RequestBody User user) {
		if(user.getProvinceId()!=null){
			String address = (addressService.selectProvince(user.getProvinceId())).getName() + "-";
			address += (addressService.selectCity(user.getCityId())).getName() + "-";
			address += (addressService.selectArea(user.getAreaId())).getName();
			user.setAddress(address);
		}
		userService.update(user);
		return Result.ok("修改成功！");
	}
	
	@PutMapping("/uploadPassword")
	public Result uploadPassword(@RequestBody UserPasswordDTO userPasswordDTO){
		User user=userService.getUser();
		if(!user.getPassword().equals(MD5Util.MD5Encode(userPasswordDTO.getOldPassword()))){
			return Result.error("原密码错误！");
		}
		user.setPassword(MD5Util.MD5Encode(userPasswordDTO.getNewPassword()));
		userService.update(user);
		return Result.ok("修改成功！");
	}
	
	@PutMapping("/resetPassword/{id}")
	public Result resetPassword(@PathVariable Integer id){
		String password=MD5Util.MD5Encode("123456");
		userService.resetPassword(id,password);
		return Result.ok("重置默认密码成功！");
	}
	
	@RequestMapping("/selectDeptCount")
	public Result selectDeptCount() {
		List<TypeCountVO> list = userService.selectDeptCount();
		return Result.ok(list);
	}
	
	@PutMapping("/updateStatus/{id}/{status}")
	public Result updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
		User user = new User();
		user.setId(id);
		user.setStatus(status);
		userService.update(user);
		return Result.ok("修改成功！");
	}
	
	@GetMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response){
		userService.exportExcel(response);
	}
	
	@RequestMapping("/importExcel")
	public Result importExcel(MultipartFile file){
		userService.importExcel(file);
		return Result.ok("导入成功！");
	}
	
	@GetMapping("/selectCount")
	public Result selectCount(){
		Long userCount = userService.selectCount();
		return Result.ok(userCount);
	}
}
